var layer = layui.layer //弹层
    ,table = layui.table //表格
form = layui.form,$ = layui.jquery,laydate = layui.laydate;
lay('.starttime').each(function(){
    laydate.render({
        elem: this
    });
});

function getAllJson(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];
        if(item["users"]){
            for(let it of item["users"]){
                item["list"].push(it)
            }
        }
        if(item["list"] && item["list"].length){
            tmparr["children"]=   this.getAllJson(item["list"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}

function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
            return this
        }
    })
}


//select over
(function () {
    //获取当前用户的部门及人员结构树
    let treeList = getCurrentDepartmentUser();

    if(treeList && treeList.list){
        let userTree = getAllJson(treeList.list);
        getxmselect("#operationCode","operationCode", userTree);
        getxmselect("#salesmanCode","salesmanCode", userTree);
    }else {
        getxmselect("#operationCode","operationCode", [{name: user.name, value: user.code}]);
        getxmselect("#salesmanCode","salesmanCode", []);
    }


    let priceTerms=[];
    //获取只包含国内贸易的价格术语
    $.ajax({
        type : 'GET',
        url:'billing/getPriceTerms',
        dataType:"json",
        async:false,
        success: function (data) {
            if (data.status == 200) {
                priceTerms = data.data;
            }
        },

    });

    if(priceTerms && priceTerms.length>0){
        let priceTermTree = getAllJson(priceTerms);
        getxmselect("#priceTermsCode","priceTermsCode", priceTermTree);
    }else {
        getxmselect("#priceTermsCode","priceTermsCode", []);
    }


})()


let loginUserCode;
layer.ready(function () {
});
table.render({
    elem: '#mains'
    ,url:'billing/getExportContentListByPage'
    , where: {
        operationCode:user.code ,
    }
    ,cols: [[
        {checkbox: true, sort : true,title:'选择'}
        ,{field: 'exportContractNo', title: '外销合同号', sort: true}
        ,{field: 'purchaseContractNo', title: '采购合同号', sort: true}
        ,{field:'billCompanyName', title:'签约公司'}
        ,{field:'billCompanyCode', hide:true}
        ,{field: 'signingDateStr', title: '签约日期', sort: true}
        ,{field:'salesmanName', title:'业务员'}
        ,{field:'salesmanCode', hide:true}
        ,{field:'operatorName', title:'操作员'}
        ,{field:'operatorCode', hide:true}
        ,{field:'customerName', title:'供应商'}
        ,{field:'customerCode', hide:true}
        ,{field:'priceTermsName', title:'价格术语'}
        ,{field:'priceTermsCode', hide:true}

    ]]
    ,id: 'mainstableid'
    ,height: 500
    ,page: true
});

form.on('submit(submitform)', function(data){
    table.reload('mainstableid', {
        page: {
            curr: 1 //重新从第 1 页开始
        }
        ,where: data.field
    }, 'data');
    return false;
});

$("#choose").on("click",function () {
    var purchaseorderdata =   table.checkStatus("mainstableid").data;
    if(purchaseorderdata.length == 0){
        layer.msg("请选择数据")
    }else{
        var oldData =  parent.table.cache["moaidetailtableid"];
        let flag=true;
        $.each(purchaseorderdata, function (index, value) {
            //外销合同号
            let exportContractNo=value.exportContractNo;
            let arr=[];
            $.ajax({
                url:'billing/getExportContractProductList',
                type:"POST",
                data:{exportContractNo:exportContractNo},
                async:false,
                success:function (data) {
                    arr=data.data;
                }
            });
            if (arr.length==0){
                flag=false;
            }
            let newArr=[];
            for (let i = 0; i < arr.length; i++) {
                let newTemp = {};
                newTemp.tempId=Number(Math.random().toString().substr(3,3) + Date.now()).toString(36);
                newTemp.saleContractCode=value.exportContractNo;
                newTemp.stockCode=value.purchaseContractNo;
                newTemp.companyName=value.billCompanyName;
                newTemp.companyCode=value.billCompanyCode;
                newTemp.supplyCode=value.customerCode;
                newTemp.supplyName=value.customerName;

                newTemp.goodsCode= arr[i].productNo;
                newTemp.specCode= arr[i].specNo;
                newTemp.goodsSpec= arr[i].normExplain;
                newTemp.goodsCname= arr[i].chineseName;
                newTemp.goodsEname= arr[i].englishName;
                newTemp.goodsCdesc= arr[i].chineseDesc;
                newTemp.goodsEdesc= arr[i].englishDesc;
                newTemp.goodsNum= arr[i].amount;
                newTemp.goodsUnit= arr[i].unit;
                newTemp.invoiceUnitPrice= arr[i].price;
                newTemp.invoiceSubtotal= arr[i].subtotal;
                newTemp.colour= arr[i].color;
                newTemp.goodsGross= arr[i].grossWeight;
                newTemp.totalGross= arr[i].grossSubtotal;
                newTemp.netWeight= arr[i].netWeight;
                newTemp.totalNet= arr[i].netSubtotal;
                newTemp.bulk= arr[i].volume;
                newTemp.purchaseUnitPrice= arr[i].price;
                newTemp.unitCost= arr[i].price;
                newTemp.costSubtotal= arr[i].subtotal;
                newTemp.declarePrice= 0;
                newTemp.totalPrice= 0;
                newTemp.productType= parseInt(arr[i].purchaseType);
                newTemp.customerInvoiceGoodsName=arr[i].customerInvoiceGoodsName;
                newTemp.customerInvoiceSpecModel=arr[i].customerInvoiceSpecModel;
                newTemp.customerMaterialsCode=arr[i].customerMaterialsCode;

                newTemp.linker = arr[i].contactPerson;
                newTemp.invoiceType= 3;//开票单据来源（1导入报关，2导入采购，3导入外销，4导入结汇）
                newArr.push(newTemp);
            }

            oldData.push.apply(oldData,newArr);
        });
        if (!flag){
            layer.msg("存在单号已完成开票的数据，请重新选择", {icon: 5});
            return false;
        }
        parent.table.reload('moaidetailtableid',{data : oldData}); //刷新主信息表格
        //执行接口
        layer.msg("保存成功", {icon: 6});
        setTimeout(function () {
            //保存成功则关闭此页面
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        },1000)
    }
})
$("#shutdown").on("click",function () {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
})